<?

class AGController
{
  var $ctrName;

  function __construct($ctrName) 
  {
    global $config;
    $this->ctrName = $ctrName;
    $this->language = 'en';
    $this->viewDirectory = 'views';
    $this->skipView = false;
    $this->headers = &$config['pageheaders'];
    $config['currentcontroller'] = &$this;
  }

  function Index()
  {
    $this->invokeModel();
    $this->showView('index');
  }
  
  function redirectUrl($url)
  {
    global $config;
    header('location: '.$url);
    die();
  }
  
  function redirect($action, $controller = '', $params = array())
  {
    AGController::redirectUrl(actionUrl($action, $controller, $params));
  }
  
  function l10n($key, $bundle = null, $language = null)
  {
    global $config;
    if ($bundle == null) $bundle = $this->ctrName;
    if ($language == null) $language = getDefault($this->language, 'en');
    $bundleKey = $bundle;
    if (!isset($config[$bundleKey]))
    {
      $config[$bundleKey] = readStringListFile('l10n/'.$bundle.'.'.$language.'.cfg');
    }
    return(getDefault($config[$bundleKey][$key], '['.$key.']'));
  }
  
  function showView($viewname = null, $controllerName = null)
  {
    global $config;
    if ($controllerName == null) $controllerName = $this->ctrName;
    if ($this->viewName == null) $this->viewName = $this->actionName;
    if ($viewname == null) $viewname = $this->viewName;
    $model = &$this->model;
    $viewFileName = $this->viewDirectory.'/'.$controllerName.'.'.$viewname.'.php'; 
		
    if (file_exists($viewFileName))
    {
      include($viewFileName);
    }
    else
    {
      logError('View template not found: "<b>'.$viewFileName.'</b>"');
    }
  }

  function getModel($modelName)
  {
    $modelClassName = $modelName.'Model';
    $modelFileName = 'models/'.$modelName.'.model.php';
    if (file_exists($modelFileName))
    {
      include_once($modelFileName);
      $modelObj = new $modelClassName($modelName, $this);
      $modelObj->parentController = &$this;
      return($modelObj);
    }
    else
    {
      logError('Model class not found: "<b>'.$modelName.'</b>"');
      return(null);
    }
  }
  
  function invokeModel($modelName = null)
  {
    if ($modelName == null) $modelName = $this->ctrName;
    $model = $this->getModel($modelName);
    if (is_object($model))
    {
      $this->model = $model;
	    return($this->model);
    }
  }
  
  function cacheAction($actionName)
  {
    $this->cacheAction[strtolower($actionName)] = true;
  }
  
  function invokeController($controller, $action = 'index', $loadmodels = array())
  {
    global $ctrObj, $config;
    $controllerFile = 'controllers/'.$controller.'.controller.php';
    $controllerClassName = $controller.'Controller';
    if (file_exists($controllerFile))
    {
      profile_point('invokeController() main');
      $_REQUEST['a'] = $action; 
      $_REQUEST['c'] = $controller; 
      include_once($controllerFile);
      $ctrObj = new $controllerClassName($controller);
      $result = &$ctrObj;
      profile_point('invokeController() object init');
      $ctrObj->actionName = $action;
      $ctrObj->viewName = getDefault($ctrObj->viewName, $action);
      $cache_name = 'ctr-'.$controller.'-'.$action;
    
      foreach ($loadmodels as $m_mount => $m_name)
        $ctrObj->{$m_mount} = $ctrObj->getModel($m_name);

      profile_point('invokeController() models');

      if (is_callable(array($ctrObj, '__init')))
      {
        $ctrObj->__init();
        profile_point('invokeController() __init');
      }
      
      if ($ctrObj->cacheAction[$action] && cache_textout($cache_name))
      {
        
      }
      else
      {
        ob_start();
        if (is_callable(array($ctrObj, $action)))
        {
          $ctrObj->{$action}();
          profile_point('invokeController() action');
          
          if (isset($ctrObj->pageTitle)) $config['pagetitle'] = $ctrObj->pageTitle;
          if (isset($ctrObj->docTitle)) $config['doctitle'] = $ctrObj->docTitle;

          if (!$ctrObj->skipView)
            $ctrObj->showView($ctrObj->viewName);
          profile_point('invokeController() view');
        }
        else
        {
          header("HTTP/1.0 404 Not Found");
          logError('The "<b>'.$controller.'</b>" controller does not support "<b>'.$action.'</b>" actions');
        }
        if ($ctrObj->cacheAction[$action])
        {
          cache_storetext($cache_name, ob_get_clean(), true);
        }
      }
    }
    else
    {
      header("HTTP/1.0 404 Not Found");
      logError('Controller class not found: "<b>'.$controller.'</b>"');
    }      
    return($result);
  }
}

class AGUserController extends AGController
{
  function __construct($ctrName) 
  {
    parent::__construct($ctrName);    
    $this->mountUsermodel = $ctrName;
    $this->afterLogin = actionUrl('index', $ctrName);
    $this->loginFailMsg = 'The username and/or password do not match.';
    $this->logoutMsg = 'You are now logged out.';
    $this->signedUpMsg = 'You have now signed up. Please check your email
      account for the confirmation message containing your password.';
    $this->captions = 
      array('username' => 'Username', 'password' => 'Password', 'submit' => 'Login', 
            'email' => 'Email', 'signup' => 'Sign Up!', 'signup-title' => 'New User Signup',
            'login-title' => 'User Login', 'logout-title' => 'Logged Out');
  }

  function Login()
  {
    include_once('lib/cq-forms.php');
    $usrModel = $this->{$this->mountUsermodel};
    $this->skipView = true;
    $form = new CQForm();
    $form->add('string', 'username', $this->captions['username']);
    $form->add('password', 'password', $this->captions['password']);
    $form->add('submit', 'submit-btn', $this->captions['submit']);
    $this->docTitle = $this->captions['login-title'];
    if ($form->submitted)
    {
      $form->getData();
      if($usrModel->login($form->ds['username'], $form->ds['password']))
        $this->redirectUrl($this->afterLogin); 
      else 
        banner($this->loginFailMsg);
    }
    $form->display();
  }
  
  function Logout()
  {
    $usrModel = $this->{$this->mountUsermodel};
    $usrModel->logout();
    $usrModel->createMenu();
    $this->docTitle = $this->captions['logout-title'];
    if (!file_exists('views/'.$this->ctrName.'.logout.php'))
    {
      $this->skipView = true;
      print($this->logoutMsg);
    }
  }
  
  function Signup()
  {
    $usrModel = $this->{$this->mountUsermodel};
    if ($usrModel->enableSignup)
    {
      $this->docTitle = $this->captions['signup-title'];
      include_once('lib/cq-forms.php');
      $this->skipView = !file_exists('views/'.$this->ctrName.'.logout.php');
      $form = new CQForm();
      $form->add('string', $usrModel->emailField, $this->captions['email']);
      $form->add('submit', 'submit-btn', $this->captions['signup']);
      if ($form->submitted)
      {
        $form->getData();
        $result = $usrModel->signup($form->ds);
        if ($result != '')
          banner($result);
        else
        {
          print($this->signedUpMsg);
          return(true);
        }
      }
      $form->display();
    }
  }
  
}

?>
